package com.heny.demo.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.WKTReader;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Point自定义TypeHandler
 *
 * @author 邢益萌
 * {@code @date} 2025/9/12 13:05
 */
@MappedTypes(org.locationtech.jts.geom.Point.class)
public class PointTypeHandler extends BaseTypeHandler<Point> {
    private final WKTReader wktReader = new WKTReader();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Point parameter, JdbcType jdbcType) throws SQLException {
        PGobject pgObject = new PGobject();
        pgObject.setType("geometry");
        //生成格式: POINT(lon lat)
        pgObject.setValue(parameter.toText());
        ps.setObject(i, pgObject);
    }

    @Override
    public Point getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String wkt = rs.getString(columnName);
        return parseWkt(wkt);
    }

    @Override
    public Point getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String wkt = rs.getString(columnIndex);
        return parseWkt(wkt);
    }

    @Override
    public Point getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String wkt = cs.getString(columnIndex);
        return parseWkt(wkt);
    }

    private Point parseWkt(String wkt) {
        if (wkt == null || wkt.isEmpty()) {
            return null;
        }
        try {
            return (Point) wktReader.read(wkt);
        } catch (Exception e) {
            System.err.println("从 WKT 解析 Point 失败: " + wkt + " - " + e.getMessage());
            return null;
        }
    }
}
